#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : ident_audio.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/26 14:32
"""

import os
import traceback
from PyQt5.QtCore import QThread, pyqtSignal
from utils.tools import request
from config import Config


class IdentAudioContextWorkerQtThread(QThread):
    """音视频识别线程"""
    result = pyqtSignal(str)
    failed = pyqtSignal(Exception)

    def __init__(self, files, headers, parent=None):
        super(IdentAudioContextWorkerQtThread, self).__init__()
        self.files = eval(files)
        self.headers = headers

    def generate_files_data(self):
        """
        生成文件上传所需的 files 参数
        :param file_paths: 文件路径列表
        :return: files 参数
        """
        files = []
        file_type_mapping = {
            '.mp4': 'video/mp4',
            '.mov': 'video/quicktime',
            '.avi': 'video/x-msvideo',
            '.mkv': 'video/x-matroska',
            '.mp3': 'audio/mpeg',
            '.wav': 'audio/wav',
            '.m4a': 'audio/m4a',
            '.aac': 'audio/aac'
        }

        for file_path in self.files:
            if os.path.exists(file_path):
                file_name = os.path.basename(file_path)
                file_extension = os.path.splitext(file_path)[1].lower()
                file_type = file_type_mapping.get(file_extension, 'application/octet-stream')
                files.append(('files', (file_name, open(file_path, 'rb'), file_type)))
            else:
                print(f"文件不存在: {file_path}")
        return files


    def run(self):
        try:
            files = self.generate_files_data()
            url = f"{Config.Host}/api/ident/speech/"
            self.headers.update({'Content-Type': 'application/json'})
            response = request(url, method='POST', headers=self.headers, data={}, files=files)
            response.raise_for_status()
            context = response.json()["transcripts"]["text"]
            self.result.emit(context)
        except Exception as e:
            traceback.print_exc()
            self.failed.emit(e)
